<template>
    <view class="content">
		<uni-search-bar placeholder="请输入关键词搜索" radius="100" cancel-button="none" v-model="kw"
		class="uni-search" @confirm="confirm" @clear="clear"/>
        <view v-if="blogs.length==0" class="none">
            <image src="/static/icons(1)/nodata.png" mode="widthFix" class="logo"></image>
            <text>{{txtNoData}}</text>
        </view>
        <view v-else v-for="(item,index) in blogs" class="item-container" @click="geGood(item.id)" >
            <text class="item-title">{{item.title}}</text>
            <rich-text :nodes="item.description" class="item-description"></rich-text>
            <image :src="item.picture" mode="widthFix" class="item-focus"></image>
            <image :src="item.user.avatar" mode="aspectFill" class="item-avatar"@click.stop="showBlogger(item.user)"></image>
            <view>
                <text v-for="(tag, idx) in item.tags" :key="tag" class="item-tage">{{tag}}</text>
            </view>
			
			<view class="icon-container">
				
				<text :class="goodIds.indexOf(item.id)>=0?'iconfont icon-xihuan ic-red':'iconfont icon-xihuan ic-gray' " @click.stop="changeGood(item.id)"></text>
				<!-- 显示标题 -->
				<!-- <image src="/static/icons(1)/ic_good.png" class="icon"></image> -->
				<!-- 文章内容 -->
				<text class="icon-text" >{{item.good}}</text>
				<!-- 图片显示 -->
				<image src="/static/icons(1)/ic_comment.png" class="icon"></image>
				<!-- 头像显示 -->
				<text class="icon-text" >{{item.comments.length}}</text>
				<image src="/static/icons(1)/ic_count.png" class="icon"></image>
				<text class="icon-text" >{{item.readCount}}</text>
			</view>
			
			<text class="iconfont icon-xiala icon-tag" @click.stop="drop(item.id)"></text>
        </view>
		<view class="bottom" v-if="blogs.length==count">
			-------已到达底部--------
		</view>		
		<dialog-shell title="博主概况" ref="shell">
			<text style="padding: 20rpx;">{{blogger}}</text>
		</dialog-shell>
    </view>
</template>

<script>

	// const red = require("../../utils/request.js")
	// import params from "../../utils/params.js"
    export default {
        data() {
            return {
                txtNoData: "抱歉，暂无数据",
                blogs: [],
                page: 0,
				size:3,
                count: -1,
				searching:false,
				kw:'',
				goodIds:[],
				blogger:''
            }
        },  
        onLoad() {
			this.$noti.add(this.$params.noti_refresh_count,this.notiCount,this)
			this.$noti.add(this.$params.noti_change_good,this.notiGood,this)
			//点赞缓存
			let ids=uni.getStorageSync(this.$params.key_good_ids)
			if(ids){
				this.goodIds=ids
			}
			//读取缓存，若存在则使用缓存给this.blogs复制，否则调下面的方法从服务器读取数据
			// let hello =uni.getStorageSync("hello")
			// if(hello){
			// 	console.log(hello + ":来自缓存");
			// 	console.log("缓存中没有找到hello");
			// }else{
			// }
			
			let blogs =uni.getStorageSync(this.$params.key_blogs)
			if(blogs){
				this.blogs=blogs
				this.count=blogs.length
				console.log(blogs[0]);
			}else{
				//加载数据
				this.getPageBlogs()
			}
        },
		onUnload(){
			this.$noti.remove(this.$params.noti_refresh_count,this)
			this.$noti.remove(this.$params.noti_change_good,this)
		},
		onPullDownRefresh(){
				this.page=0
				this.count=-1
				this.blogs=[]
				this.getPageBlogs()
				this.kw=''
		},	
		onReachBottom(){
			if(this.searching || this.blogs.length== this.count){
				return
			}
			this.page++
			this.getPageBlogs()
		},	
        methods: {
			showBlogger(user){
							this.blogger="作者："+user.nickName+"\n联系方式："+user.email
							this.$refs.shell.showDialog()
						},
			notiGood(info){
				let id=info.id
				let count=info.count
				let ids=uni.getStorageSync(this.$params.key_good_ids)
				if(ids){
					this.goodIds=ids
				}
				this.blogs.forEach(b=>{
					if(b.id==id){
						b.good=count
					}
				})
			},
			notiCount(info){
				console.log("接收到通知refresh count");
				let id = info.id
				let count =info.count
			},
			
			refreshReadCount(id,count){
				this.blogs.forEach(b=>{
					if(b.id==id){
						b.readCount=count
					}
				})
			},
			toBlogDetail(id) {
				uni.navigateTo({
					url: '/pages/blog/blog?id=' + id
					});
				},
			geGood(id){
			 uni.navigateTo({
			 	url: '/pages/blog/blog?id='+id,
			 	success: res => {},
			 	fail: () => {},
			 	complete: () => {}
			 });
			},
			drop(id){
				uni.showActionSheet({
					itemList:["收藏","删除","举报"],
					success:res=>{  
						switch(res.tapIndex){
							case 0:
							uni.showToast({
								title:'功能待完善！'
							});
							break;
							case 1:
							uni.showModal({
								title:'警告',
								content:'确认要删除吗？',
								showCancel:true,
								cancelText:'算了',
								confirmText:'删除',
								success:res=>{
									if(res.confirm){
										uni.showToast({
											title:'没有删除权限，请登录',
											icon:'none'
										});
									}
								},
								fail:() =>{},
								compile:()=>{}
							});
						}
					},
					fail:() =>{},
					compile:()=>{}
				});
			},
			changeGood(id){
				let good =true//代表当前是点赞还是取消点赞
				if(this.goodIds.indexOf(id)>=0){
					good =false
				}
				if(good){
					//1.把当前blog的id保存到缓存,2.把点赞数量+1发送到服务器
					this.goodIds =[...this.goodIds,id]
				}else{
					let index =this.goodIds.indexOf(id)
					if(index>= 0){
						//1.this.goodIds.splice(index,1) splice靠循环遍历来实现
						//2.this.goodIds.shift() shift删除第一个元素
						//3.this.goodIds.pop() pop删除第一个元素
						this.goodIds[index]=this.goodIds[this.goodIds.length - 1]
						this.goodIds.pop()
					}
				}
				uni.setStorageSync(this.$params.key_good_ids,this.goodIds)
				this.postGood(id,good)
			},
			postGood(id,good){
				uni.showLoading({
					title:'点赞...',
					mask:false
				});
				let url = this.$params.host
				let action= good? this.$params.action_good : this.$params.action_del_good
				url+=action
				let data={
					"id": id
				}
				this.$req.postQuery(url,data,res=>{
					// console.log(res);
					this.blogs.forEach(blog=>{
						if(blog.id==id){
							blog.good=res.data.data
						}
					})
				},()=>{
					uni.hideLoading()
				})
			},
			confirm(e) {
				console.log(e)
				console.log(this.kw)
				let kw =e.value
				if(kw.length >0){
					this.searching=true
					this.blogs=[]
					this.page=0
					this.count= -1
					uni.showLoading({
						title: '搜索中....',
						mask: false
					});
					this.$req.get(this.$params.host+this.$params.action_search+kw,res=>{
						// console.log(res)
						res.data.data.forEach(blog=>{
							blog.picture = this.$params.host + blog.picture
							blog.user.avatar = this.$params.host + blog.user.avatar
							this.blogs=[...this.blogs,blog];
						})
					},()=>{
					uni.hideLoading()
					})
				}			
			},
			clear(){
				this.searching = false
				this.blogs = []
				this.page = 0
				this.getPageBlogs()
			},
			getPageBlogs(){
				console.log("获取远程数据");
				let header={
					"content-type":"application/json;charset=UTF-8",
					"page":this.page,
					"size":this.size
					}
				this.$req.getWithParams(this.$params.host+this.$params.action_blogs_page,header,res=>{
					res.data.data.forEach(blog=>{
					    blog.picture =this.$params.host + blog.picture
					    blog.user.avatar =this.$params.host + blog.user.avatar
				})
				// this.blogs = this.blogs.concat(res.data.data)
				this.blogs = [...this.blogs,...res.data.data]
				this.count = parseInt(res.data.message)
				//将获取的最新数据保存到缓存
				uni.setStorageSync("blogs",this.blogs)
				},()=>{
					uni.stopPullDownRefresh()
				})
				
			},
            getTopBlogs(){
				this.$req.get(this.$params.host+this.$params.action_top_blogs,res =>{
					console.log(res.data)
                        res.data.data.forEach(blog=>{
                            blog.picture =this.$params.host + blog.picture
                            blog.user.avatar =this.$params.host + blog.user.avatar
                        })
                        // console.log(res.data.data);
                        this.blogs = res.data.data
                    // },
                    // fail: () => {
                    //     console.log(err);
                    // },
                    // complete: () => {}
                })
            }
        }
    }
</script>

<style>
    @import url("index.css");
</style>